package com.eastfair.notice.listener;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.eastfair.annotation.base.LanguageTypeEnum;
import com.eastfair.enums.MsgTypeEnum;
import com.eastfair.notice.dto.MsgMqDTO;
import com.eastfair.notice.dto.MsgSendDTO;
import com.eastfair.notice.entity.MsgLog;
import com.eastfair.notice.service.MsgLogService;
import com.eastfair.projectcore.entity.MsgTemplate;
import com.eastfair.third.email.EmailUtil;
import com.eastfair.third.email.model.EmailConfig;
import com.eastfair.third.email.model.EmailField;
import com.eastfair.third.email.model.EmailParam;
import com.eastfair.third.model.MessageResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 邮件发送mq消费
 * @ClassName EmailSendListener
 * @Description 邮件发送mq消费
 * @Author liuxiaobai
 * @Date 2021/8/5 8:03 下午
 * @Version 1.0
 */
@Component
public class EmailSendListener {
    private static final Logger logger = LoggerFactory.getLogger(EmailSendListener.class);

    @Autowired
    private MsgLogService msgLogService;

    @JmsListener(destination = "${activemq.queue.emailSend}")
    public void handleMessage(String json) {
        try {
            MsgMqDTO email = JSON.parseObject(json, MsgMqDTO.class);
            EmailConfig config = email.getEmailConfig();
            MsgSendDTO sendDTO = email.getMsgSendDTO();
            MsgTemplate template = email.getTemplate();
            if (config == null || sendDTO == null || template == null) {
                return;
            }
            String receive = sendDTO.getEmail();
            if (StrUtil.isEmpty(receive)) {
                return;
            }
            //邮件发送组件参数拼接
            EmailParam param = EmailParam.builder()
                    .fromName(sendDTO.getSign())
                    .build();

            //根据语言set对应主题和内容
            if (LanguageTypeEnum.EN.equals(sendDTO.getLanguageType())) {
                param.setSubject(template.getEnSubject());
                param.setTemplate(template.getEnContent());
            } else {
                param.setSubject(template.getSubject());
                param.setTemplate(template.getContent());
            }

            //替换域类型转换
            if (sendDTO.getFields() != null && !sendDTO.getFields().isEmpty()) {
                List<EmailField> fields = new ArrayList<>();
                sendDTO.getFields().forEach(field -> fields.add(EmailField.builder()
                        .name(field.getFieldEnum().getField())
                        .value(field.getValue())
                        .build()));
                param.setFields(fields);
            }

            param.setEmailAddress(receive);

            MessageResult result = EmailUtil.send(config,param);
            //加入日志
            msgLogService.save(MsgLog.builder()
                    .projectId(sendDTO.getProjectId())
                    .exhibitionId(sendDTO.getExhibitionId())
                    .type(MsgTypeEnum.EMAIL.name())
                    .tempId(template.getId())
                    .receiveType(sendDTO.getReceiveType().name())
                    .receiveId(sendDTO.getReceiveUserId())
                    .receive(receive)
                    .content(param.getTemplate())
                    .status(result.getStatus())
                    .errMsg(result.getErrorMsg())
                    .build());
        } catch (Exception e) {
            logger.error("邮件mq消费",e);
        }
    }

}
